package com.ruochen.common.base;


import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.StringUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * base fragment
 * Created by SongJun on 2016/11/28.
 */
public abstract class BaseFragment<VB extends ViewDataBinding> extends RxFragment {

    protected VB viewBinding;
    protected BaseActivity mContext;
    protected LoadingPopupView mSVProgressHUD;
    private View mRootView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        mContext = (BaseActivity) getActivity();
        beforeSetView(savedInstanceState);
        if (mRootView != null) {
            ViewGroup parent = (ViewGroup) mRootView.getParent();
            if (parent != null) {
                parent.removeView(mRootView);
            }
        }
        Type superclass = getClass().getGenericSuperclass();
        Class<?> aClass = (Class<?>) ((ParameterizedType) superclass).getActualTypeArguments()[0];
        try {
            Method method = aClass.getDeclaredMethod("inflate", LayoutInflater.class);
            viewBinding = (VB) method.invoke(null, getLayoutInflater());
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        mRootView = viewBinding.getRoot();
        if (isRegisterEventBus()) {
            EventBus.getDefault().register(this);
        }
        return mRootView;
    }

//    protected abstract int getLayout();

    protected void beforeSetView(Bundle savedInstanceState) {
    }

    protected void afterSetView(Bundle savedInstanceState) {
    }

    protected void setTitleBar(Bundle savedInstanceState) {
    }

    protected void initView(Bundle savedInstanceState) {
    }


    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected boolean isRegisterEventBus() {
        return false;
    }

    public BaseActivity getMyActivity() {
        return (BaseActivity) getActivity();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setTitleBar(savedInstanceState);
        initView(savedInstanceState);
        afterSetView(savedInstanceState);
    }

    protected View getRootView(){
        return mRootView;
    }

    @Override
    public void onDestroy() {
        if (mSVProgressHUD != null) {
            if (mSVProgressHUD.isShow()) mSVProgressHUD.dismiss();
            mSVProgressHUD = null;
        }
        if (isRegisterEventBus() && EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
        mContext = null;
        mRootView = null;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public void showToast(int resId) {
        showToast(getResources().getString(resId));
    }

    public void showToast(String text) {
        if (mContext == null) return;
        mContext.showToast(text);
    }

    public void showLoading(){
        showLoading("加载中");
    }

    public void showLoading(String waitLabel) {
        if (mSVProgressHUD != null) {
            if(mSVProgressHUD.isShow())  mSVProgressHUD.dismiss();
            mSVProgressHUD = null;
        }
        /*mSVProgressHUD = KProgressHUD.create(getMContext())
                .setCancellable(isCancelRequestOnClickBack())
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel(waitLabel)
                .setDetailsLabel(null);
        mSVProgressHUD.show();*/
        mSVProgressHUD = new XPopup.Builder(mContext)
                .dismissOnBackPressed(isCancelRequestOnClickBack())
                .dismissOnTouchOutside(isCancelRequestOnClickBack())
                .isDestroyOnDismiss(true)
                .hasShadowBg(false)
                .asLoading(StringUtils.isTrimEmpty(waitLabel) ? "正在加载中" : waitLabel);
        mSVProgressHUD.show();
    }


    public void hide() {
        if (mSVProgressHUD != null) {
            if(mSVProgressHUD.isShow()) mSVProgressHUD.delayDismiss(300);
            mSVProgressHUD = null;
        }
    }

    public void removeCallBack(ApiCallback callback) {

    }

    public Context getMContext() {
        return mContext;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    public boolean isLogin() {
        return mContext.isLogin();
    }

    public String getUserToken() {
        return mContext.getUserToken();
    }

    public String getUserId() {
        return mContext.getUserId();
    }

    public boolean isFinish() {
        boolean a = mContext == null || mContext.isFinishing();
        if (Build.VERSION.SDK_INT < 17) {
            return a;
        } else {
            return a || mContext.isDestroyed() || mContext.getFragmentManager().isDestroyed();
        }
    }

    public String getStringSource(int res) {
        return getString(res);
    }

    public void gotoLogin() {
        if (getMyActivity() != null)
            getMyActivity().gotoLogin();
    }

    public void startActivity(Class<? extends Activity> activity) {
        if (mContext != null) {
            mContext.startActivity(activity, null);
        }
    }

    public void startActivity(Class<? extends Activity> activity, Bundle bundle) {
        if (mContext != null) {
            mContext.startActivity(activity, bundle);
        }
    }

    public void startActivityAnimBottom(Class<? extends Activity> activity) {
        if (mContext != null) {
            mContext.startActivityAnimBottom(activity);
        }
    }

    public void startActivityAnimBottom(Class<? extends Activity> activity, Bundle bundle) {
        if (mContext != null) {
            mContext.startActivityAnimBottom(activity, bundle);
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (isCancelRequestOnClickBack()) {
                if (mSVProgressHUD != null && mSVProgressHUD.isShow()) {
                    mSVProgressHUD.dismiss();
                    mSVProgressHUD = null;
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 点击返回取消正在请求的对话框
     *
     * @return
     */
    public boolean isCancelRequestOnClickBack() {
        return true;
    }

}
